package com.asohofrucol.web;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;

import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.asohofrucol.dto.AsohofrucolSessionDTO;
import com.asohofrucol.dto.UserDTO;
import com.asohofrucol.service.UserService;
import com.asohofrucol.web.util.CredentialsHelperUtil;

public class LoginController implements Serializable {
	private static final long serialVersionUID = -2152389656664659476L;
	private String userName;
	private String password;
	private boolean login = false;
	@Autowired
	UserService userService;
	@Autowired
	private AsohofrucolSessionDTO aSession;

	public void login(ActionEvent actionEvent) {
		RequestContext context = RequestContext.getCurrentInstance();
		FacesMessage msg = null;
		UserDTO userDto = userService.findByUserName(this.userName);
		int result = -1;
		if (userDto != null) {
			result = CredentialsHelperUtil.compareCredentials(this.password,
					userDto.getPassword());
		}
		if (result == CredentialsHelperUtil.CODE_OK) {
			login = true;
			msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Bienvenid@",
					this.userName);
		} else if (result == CredentialsHelperUtil.WRONG_PASSWORD) {
			login = false;
			msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error",
					"Pasword Incorrecta");
		} else {
			login = false;
			msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error",
					"Error en credenciales");
		}

		FacesContext.getCurrentInstance().addMessage(null, msg);
		context.addCallbackParam("logIn", login);
		if (login) {
			aSession.setUserInfo(userDto);
			context.addCallbackParam("view", "owner/list_owner_data.xhtml");
		}
	}

	public void logout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
		session.invalidate();
		login = false;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isLogin() {
		return login;
	}

	public void setLogin(boolean login) {
		this.login = login;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}